﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Phoenix.Common;
using Phoenix.Common.Helper;
using Phoenix.Common.Util;
using Phoenix.Cache;
using Phoenix.Service.Model;
using Phoenix.Service.Contracts;
using Phoenix.Service;

namespace Phoenix.AdminSite.Controllers
{
	[HandleError]
    public class HomeController : ControllerBase
	{
        ICacheProvider _cacheProvider = CacheProviderFactory.HashTable().CreateCacheProvider();
        IAdminUserService IAdminUser = new AdminUserService();

        private const string adminUserPrefix = "Phoenix:AdminUser::";

		public ActionResult Index()
		{
			ViewData["Message"] = "欢迎使用 ASP.NET MVC!";

			return View();
		}

		/// <summary>
		/// 欢迎界面
		/// </summary>
		/// <returns></returns>
		public ActionResult Welcome()
		{
			return View();
		}

        public ActionResult Default()
        {
            return View();
        }

		public ActionResult About()
		{
			return View();
		}

        public ActionResult Login()
        {
            return View();
        }

        public ActionResult DoLogin(FormCollection collection)
        {
            string userName = collection["txtUserName"];
            string password = collection["txtPassword"];

            AdminUserModel model = IAdminUser.GetByUserName(userName);

            string token = RandomHelper.GetRandomStr(12);
            long timestamp = System.DateTime.Now.Ticks;


            string logonStr = MD5.GetMD5String(model.UserID.ToString() + token + timestamp.ToString());

            if (!_cacheProvider.Contains(adminUserPrefix + token))
            {
                _cacheProvider.Add(adminUserPrefix + logonStr, model);
            }

            Cookie.SetCookie("logon", logonStr, "admin.86tc.com");

            if (!string.IsNullOrEmpty(Request.QueryString["done"]))
            {
                Redirect(Request.QueryString["done"]);
            }
            else
            {
                RedirectToAction("Welcome");
            }

            return null;
            
        }
	}
}
